<script setup>
import { reactive, ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { registerAPI, loginAPI } from '@/api/userAPI'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token'

//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)


const ruleFormRef = ref()

const checkUsername = (rule, value, callback) => {
    if (value === '') {
        return callback(new Error('请输入用户名'))
    } else if (value.length < 6 || value.length > 16) {
        callback(new Error('用户名长度在6-16位之间'))
    } else {
        callback()
    }
}

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (value.length < 6 || value.length > 16) {
        callback(new Error('密码长度在6-16位之间'))
    }
    else {
        if (ruleForm.rePassword !== '') {
            if (!ruleFormRef.value) return
            ruleFormRef.value.validateField('rePassword')
        }
        callback()
    }
}

const validatePass2 = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== ruleForm.password) {
        callback(new Error("两次输入密码不一致"))
    } else {
        callback()
    }
}
// 这里必须使用 reactive，否则验证会报错
const ruleForm = reactive({
    username: '',
    password: '',
    rePassword: '',
})
// 这里必须使用 reactive，否则验证会报错
const rules = reactive({
    password: [{ validator: validatePass, trigger: 'blur' }],
    rePassword: [{ validator: validatePass2, trigger: 'blur' }],
    username: [{ validator: checkUsername, trigger: 'blur' }],
})

const registerForm = (formEl) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            let res = await registerAPI({ 'username': ruleForm.username, 'password': ruleForm.password, 'rePassword': ruleForm.rePassword })
            ElMessage({
                type: 'success',
                message: '注册成功'
            })
        } else {
            console.log('提交失败，请再次检查所填信息是否正确!')
        }
    })
}

// 登录页面逻辑
const router = useRouter()
const tokenStrore = useTokenStore()

const loginForm = async (formEl) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            let res = await loginAPI({ 'username': ruleForm.username, 'password': ruleForm.password, 'rePassword': ruleForm.password })
            // token保存到pinia
            tokenStrore.setToken(res.data)

            ElMessage({
                type: 'success',
                message: '登录成功'
            })
            // 登录成功后，跳转到首页
            router.push('/')
        } else {
            console.log('提交失败，请再次检查所填信息是否正确!')
        }
    })
}

// 清空表单
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 注册表单 -->
            <el-form ref="ruleFormRef" size="large" autocomplete="off" v-if="isRegister" :model="ruleForm"
                :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item label="用户名：" prop="username">
                    <el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input :prefix-icon="Lock" type="password" v-model="ruleForm.password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="确认密码：" prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" v-model="ruleForm.rePassword" placeholder="请再次输入密码" />
                </el-form-item>

                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="registerForm(ruleFormRef)">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false; resetForm(ruleFormRef)">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="ruleFormRef" size="large" autocomplete="off" v-else :model="ruleForm" :rules="rules">
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item label="用户名：" prop="username">
                    <el-input :prefix-icon="User" v-model="ruleForm.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input :prefix-icon="Lock" type="password" v-model="ruleForm.password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="loginForm(ruleFormRef)">
                        登录
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true; resetForm(ruleFormRef)">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
            url('@/assets/login_bg.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>